package shc.graduation.ui;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;

import org.litepal.crud.DataSupport;

import shc.graduation.R;
import shc.graduation.bean.CodeInfo;
import shc.graduation.bean.MyCollection;
import shc.graduation.bean.PaoWangArticle;
import shc.graduation.bean.PaperInfo;
import shc.graduation.utils.FileUtil;
import shc.graduation.utils.ServerUtil;
import shc.graduation.utils.SystemBarTintManager;
import shc.graduation.view.ProgressWheel;

public class WebViewActivity extends AppCompatActivity {

    private static final String SDPATH = FileUtil.getMainPath() + "/WebCache";
    public static final String WEB_URL = "WebUrl";

    public static final String OBJECT = "object";
    public static final String OBJECT_TYPE = "object_type";
    //   代表类型为：开源代码
    public static final int OPEN_CODE = 0;
    //   代表类型为：泡网文章
    public static final int PAOWANG = 1;
    //   代表类型为：好东西日报
    public static final int PAPER = 2;
    //   代表类型为：我的收藏
    public static final int MYCOLLECTION = 3;

    protected Toolbar mToolBar = null;
    protected Toast mToast = null;
    protected Context mContext = null;

    private WebView mWebview;
    private ProgressWheel mProgressWheel;
    private WebSettings mWebSettings;
    // 8为默认值，0代表codeinfo,1代表泡网文章，2代表好东西日报，3代表我的收藏
    private int mObjectType = 8;
    private Intent mIntent = null;
    private CodeInfo mCodeInfo = null;
    private PaoWangArticle mPaoWangArticle = null;
    private PaperInfo mPaperInfo = null;
    private MyCollection mMyCollection = null;

    private FloatingActionMenu menuRed;
    private FloatingActionButton fab1;
    private FloatingActionButton fab2;

    private String mWebUrl = null;

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mProgressWheel.setVisibility(View.VISIBLE);//显示进度框
                    break;
                case 1:
                    mProgressWheel.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.fab1:
                    shareToFriends();
                    break;

                case R.id.fab2:
                    setMyCollection();
                    break;
            }

            menuRed.close(true);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        onPreSetContentView();
        int contentViewId = getContentViewId();
        if (contentViewId <= 0) {
            throw new IllegalArgumentException("the contentview layout id must be setted");
        }

        setContentView(contentViewId);
        View decorView = findViewById(android.R.id.content);
        onPostSetContentView();
        onCreate(savedInstanceState, decorView);
    }

    /**
     * 设置ContentView后
     */
    private void onPostSetContentView() {
        mContext = this;
        mToolBar = (Toolbar) findViewById(R.id.webview_toolbar1);
        findViews();
        setSupportActionBar(mToolBar);
    }

    /**
     * 设置contentView前
     */
    private void onPreSetContentView() {
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                //状态栏透明，需要在创建SystemBarTintManager之前调用
                setTranslucentStatus(true);
            }
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            //设置状态栏与ToolBar的颜色保持一致
            tintManager.setStatusBarTintResource(R.color.colorPrimaryDark);
        }
    }

    private void setTranslucentStatus(boolean on) {
        Window window = getWindow();
        WindowManager.LayoutParams winParams = window.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        window.setAttributes(winParams);
    }

    public void enabledBackButton() {
        mToolBar.setNavigationIcon(R.mipmap.ic_back);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void onCreate(Bundle saveInsatanceState, View decorView) {
        enabledBackButton();
        mIntent = getIntent();
        mWebUrl = mIntent.getStringExtra(WEB_URL);

        if (TextUtils.isEmpty(mWebUrl)) {
            toast("地址是空的");
            finish();
        }

        mHandler.sendEmptyMessage(0);
        mWebview.setWebViewClient(new MyWebviewClient());
        mWebSettings = mWebview.getSettings();

        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT,无网络时，使用LOAD_CACHE_ELSE_NETWORK
        mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 设置缓存模式
        // 设置Application caches缓存目录
        mWebSettings.setAppCachePath(SDPATH);
        // 开启Application Cache功能
        mWebSettings.setAppCacheEnabled(true);

        if (Build.VERSION.SDK_INT >= 19) {
            mWebSettings.setLoadsImagesAutomatically(true);
        } else {
            mWebSettings.setLoadsImagesAutomatically(false);
        }
        mWebview.loadUrl(mWebUrl);
    }


    public int getContentViewId() {
        return R.layout.activity_web_view;
    }

    public void findViews() {
        mToolBar.setTitle("返回");
        mToolBar.setTitleTextColor(getResources().getColor(R.color.white));

        mWebview = (WebView) findViewById(R.id.codedetail_webview);
        mProgressWheel = (ProgressWheel) findViewById(R.id.codedetail_progress);

        menuRed = (FloatingActionMenu) findViewById(R.id.webview_floatbutton_menu);
        fab1 = (FloatingActionButton) findViewById(R.id.fab1);
        fab2 = (FloatingActionButton) findViewById(R.id.fab2);

        fab1.setOnClickListener(clickListener);
        fab2.setOnClickListener(clickListener);

        menuRed.setClosedOnTouchOutside(true);
        menuRed.setOnMenuButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeLikeIcon();

                menuRed.toggle(true);
            }
        });

    }

    private void changeLikeIcon() {
        if (mObjectType == 8) {
            mObjectType = mIntent.getIntExtra(OBJECT_TYPE, 8);
        }

        MyCollection myCollection = null;
        switch (mObjectType) {
            case 0:
                CodeInfo codeInfo;
                if (mCodeInfo == null) {
                    codeInfo = (CodeInfo) mIntent.getSerializableExtra(OBJECT);
                } else {
                    codeInfo = mCodeInfo;
                }

                codeInfo = DataSupport.find(CodeInfo.class, codeInfo.getId(), true);
                mCodeInfo = codeInfo;
                myCollection = codeInfo.getMyCollection();
                changeLikeIcon(myCollection);
                break;

            case 1:
                PaoWangArticle paoWangArticle;
                if (mPaoWangArticle == null) {
                    paoWangArticle = (PaoWangArticle) mIntent.getSerializableExtra(OBJECT);
                } else {
                    paoWangArticle = mPaoWangArticle;
                }

                paoWangArticle = DataSupport.find(PaoWangArticle.class, paoWangArticle.getId(), true);
                mPaoWangArticle = paoWangArticle;
                myCollection = paoWangArticle.getMyCollection();
                changeLikeIcon(myCollection);
                break;

            case 2:
                PaperInfo paperInfo;
                if (mPaperInfo == null) {
                    paperInfo = (PaperInfo) mIntent.getSerializableExtra(OBJECT);
                } else {
                    paperInfo = mPaperInfo;
                }

                paperInfo = DataSupport.find(PaperInfo.class, paperInfo.getId(), true);
                mPaperInfo = paperInfo;
                myCollection = paperInfo.getMyCollection();
                changeLikeIcon(myCollection);
                break;

            case 3:
                MyCollection mycollection = (MyCollection) mIntent.getSerializableExtra(OBJECT);
                myCollection = DataSupport.find(MyCollection.class, mycollection.getId(), true);
                mMyCollection = myCollection;
                changeLikeIcon(myCollection);
                break;
        }

    }

    private void changeLikeIcon(MyCollection myCollection) {
        if (myCollection != null) {
            fab2.setImageResource(R.mipmap.ic_favorite_black_24dp);
        } else {
            fab2.setImageResource(R.mipmap.ic_favorite_border_white_24dp);
        }
    }

    public void toast(String toastString) {
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), toastString, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(toastString);
        }
        mToast.show();
    }

    private class MyWebviewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            view.loadUrl(url);
            // startActivity(i);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mHandler.sendEmptyMessage(1);
            if (!mWebSettings.getLoadsImagesAutomatically()) {
                mWebSettings.setLoadsImagesAutomatically(true);
            }
        }
    }

    private void shareToFriends() {
        String url = null;
        switch (mObjectType) {
            case 0:
                url = mCodeInfo.getGithubUrl();
                break;

            case 1:
                url = ServerUtil.PAOWANG_URL + mPaoWangArticle.getContentUrl();
                break;

            case 2:
                url = mPaperInfo.getFromAddress();
                break;

            case 3:
                url = mMyCollection.getAddressURL();
                break;
        }

        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, url);
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    private void setMyCollection() {
        switch (mObjectType) {
            case 0:
                CodeInfo codeInfo = mCodeInfo;
                if (codeInfo.getMyCollection() == null) {
                    // 添加收藏
                    MyCollection myCollection = new MyCollection();
                    myCollection.setAddressURL(ServerUtil.PAOWANG_URL + codeInfo.getContentUrl());
                    if (!TextUtils.isEmpty(codeInfo.getPhotoUrl())) {
                        myCollection.setPhotoURL(ServerUtil.PAOWANG_URL + codeInfo.getPhotoUrl());
                    }

                    myCollection.setTitle(codeInfo.getName());
                    myCollection.setType(0);
                    myCollection.setTime(codeInfo.getTime());
                    myCollection.setContent(codeInfo.getContent());
                    myCollection.setCodeInfo(codeInfo);
                    myCollection.save();

                    codeInfo.setMyCollection(myCollection);
                    codeInfo.save();

                    toast("已收藏");
                } else {
                    // 取消收藏
                    MyCollection myCollection = codeInfo.getMyCollection();
                    myCollection.setCodeInfo(null);
                    myCollection.save();

                    codeInfo.setMyCollection(null);
                    codeInfo.save();

                    myCollection.delete();

                    toast("已取消收藏");
                }
                break;
            case 1:
                PaoWangArticle paoWangArticle = mPaoWangArticle;
                if (paoWangArticle.getMyCollection() == null) {
                    // 添加收藏
                    MyCollection myCollection = new MyCollection();
                    myCollection.setAddressURL(ServerUtil.PAOWANG_URL + paoWangArticle.getContentUrl());
                    if (!TextUtils.isEmpty(paoWangArticle.getPhotoUrl())) {
                        myCollection.setPhotoURL(ServerUtil.PAOWANG_URL + paoWangArticle.getPhotoUrl());
                    }

                    myCollection.setTitle(paoWangArticle.getTitle());
                    myCollection.setType(1);
                    myCollection.setTime(paoWangArticle.getPublishDate());
                    myCollection.setContent(paoWangArticle.getContent());
                    myCollection.setPaoWangArticle(paoWangArticle);
                    myCollection.save();

                    paoWangArticle.setMyCollection(myCollection);
                    paoWangArticle.save();

                    toast("已收藏");
                } else {
                    // 取消收藏
                    MyCollection myCollection = paoWangArticle.getMyCollection();
                    myCollection.setPaoWangArticle(null);
                    myCollection.save();

                    paoWangArticle.setMyCollection(null);
                    paoWangArticle.save();

                    myCollection.delete();

                    toast("已取消收藏");
                }
                break;

            case 2:
                PaperInfo paperInfo = mPaperInfo;
                if (paperInfo.getMyCollection() == null) {
                    // 添加收藏
                    MyCollection myCollection = new MyCollection();
                    myCollection.setAddressURL(paperInfo.getFromAddress());
                    myCollection.setPhotoURL(paperInfo.getPhotoUrl());
                    myCollection.setTitle(paperInfo.getAuthor());
                    myCollection.setType(2);
                    myCollection.setTime(paperInfo.getPaperTime());
                    myCollection.setContent(paperInfo.getContent());
                    myCollection.setPaperInfo(paperInfo);
                    myCollection.save();

                    paperInfo.setMyCollection(myCollection);
                    paperInfo.save();

                    toast("已收藏");
                } else {
                    // 取消收藏
                    MyCollection myCollection = paperInfo.getMyCollection();
                    myCollection.setPaperInfo(null);
                    myCollection.save();

                    paperInfo.setMyCollection(null);
                    paperInfo.save();

                    myCollection.delete();

                    toast("已取消收藏");
                }
                break;

            case 3:
                MyCollection myCollection = mMyCollection;
                // 取消收藏
                switch (myCollection.getType()) {
                    case 0:
                        CodeInfo codeinfo = myCollection.getCodeInfo();
                        codeinfo.setMyCollection(null);
                        codeinfo.save();

                        myCollection.setCodeInfo(null);

                        mCodeInfo = DataSupport.find(CodeInfo.class, codeinfo.getId(), true);
                        mObjectType = 0;
                        break;

                    case 1:
                        PaoWangArticle paowangArticle = myCollection.getPaoWangArticle();
                        paowangArticle.setMyCollection(null);
                        paowangArticle.save();

                        myCollection.setPaoWangArticle(null);

                        mPaoWangArticle = DataSupport.find(PaoWangArticle.class, paowangArticle.getId(), true);
                        mObjectType = 1;
                        break;

                    case 2:
                        PaperInfo paPerInfo = myCollection.getPaperInfo();
                        paPerInfo.setMyCollection(null);
                        paPerInfo.save();

                        myCollection.setPaperInfo(null);

                        mPaperInfo = DataSupport.find(PaperInfo.class, paPerInfo.getId(), true);
                        mObjectType = 2;
                        break;
                }
                myCollection.save();
                myCollection.delete();
                toast("已取消收藏");
                break;
        }

    }

    @Override
    protected void onDestroy() {

        mHandler.removeCallbacksAndMessages(null);

        super.onDestroy();
    }
}
